#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <functional>
#include <cstring>
#include <cerrno>
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h>
#include "err.hpp"
#include "Task.hpp"
#include "threadPool_V4.hpp"
#include "log.hpp"

namespace tcp_server
{
    const static uint16_t default_port = 8080;
    const static int backlog = 32;
    using func_t = std::function<std::string(std::string)>;

    class TcpServer;
    class ThreadData
    {
    public:
        ThreadData(int fd, const std::string& ip, const uint16_t& port, TcpServer* ts)
            :sock(fd)
            ,clientip(ip)
            ,clientport(port)
            ,current(ts)
        {}
        int sock;
        std::string clientip;
        uint16_t clientport;
        TcpServer* current;
    };

    class TcpServer
    {
    public:
        TcpServer(func_t func, uint16_t port = default_port)
            :func_(func)
            ,port_(port)
        {}
        void InitServer()
        {
            listensock_ = socket(AF_INET, SOCK_STREAM, 0);
            if (listensock_ < 0)
            {
                // std::cerr << "create socket error" << std::endl;
                logMessage(FATAL, "create socket error");
                exit(SOCKET_ERR);
            }
            logMessage(INFO, "create socket success");
            // std::cout << "create socket success" << std::endl; 

            struct sockaddr_in local;
            local.sin_family = AF_INET;
            local.sin_port = htons(port_);
            local.sin_addr.s_addr = INADDR_ANY;

            if (bind(listensock_, (struct sockaddr*)&local, sizeof(local)) < 0)
            {
                std::cerr << "bind socket error" << std::endl;
                exit(BIND_ERR);
            }
            std::cout << "bind socket success" << std::endl; 

            if (listen(listensock_, backlog) < 0)
            {
                std::cerr << "listen socket error" << std::endl;
                exit(LISTEN_ERR);
            }
            std::cout << "listen socket success" << std::endl; 
        }
        void Start()
        {
            // signal(SIGCHLD, SIG_IGN); 推荐 
            quit_ = false;
            while (!quit_)
            {
                struct sockaddr_in client;
                socklen_t len = sizeof(client);
                int sock = accept(listensock_, (struct sockaddr*)&client, &len);
                if (sock < 0)
                {
                    std::cerr << "accept error" << std::endl;
                    continue;
                }
                std::string clientip = inet_ntoa(client.sin_addr);
                uint16_t clientport = ntohs(client.sin_port);
                
                // std::cout << "获取新连接成功:" << sock << " from " << listensock_ << ", "
                //         << clientip << "-" << clientport << std::endl;
                logMessage(INFO, "获取新连接成功: %d from %d, %s-%d", sock, listensock_, clientip.c_str(), clientport);

                // service(sock, clientip, clientport);

                // v2 多进程版本
                // pid_t id = fork();
                // if (id < 0)
                // {
                //     close(sock);
                //     continue;
                // }
                // else if (id == 0)
                // {
                //     close(listensock_);
                //     //if (fork() > 0) exit(0);
                //     service(sock, clientip, clientport);
                //     exit(0);
                // }
                // else
                // {
                //     //close(sock);
                //     pid_t ret = waitpid(id, nullptr, 0);// 不推荐 waitpid(id, nullptr, WNOHANG)
                //     if (ret == id) std::cout << "wait child " << id << " success" << std::endl;
                // }

                // v3 多线程版本
                // pthread_t tid;
                // ThreadData* td = new ThreadData(sock, clientip, clientport, this);
                // pthread_create(&tid, nullptr, threadRoutine, td);

                // v4 线程池版本
                Task t(sock, clientip, clientport, std::bind(&TcpServer::service, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
                ThreadPool<Task>::getinstance()->pushTask(t);
            }
        }

        static void* threadRoutine(void* args)
        {
            pthread_detach(pthread_self());

            ThreadData* td = static_cast
            <ThreadData*>(args);
            td->current->service(td->sock, td->clientip, td->clientport);
            delete td;
            return nullptr;
        }

        void service(int sock, const std::string& clientip, const uint16_t& clientport)
        {
            std::string who = clientip + "=" + std::to_string(clientport);
            char buffer[1024];
            ssize_t s = read(sock, buffer, sizeof(buffer)-1);
            if (s > 0)
            {
                buffer[s] = 0;
                std::string res = func_(buffer);
                // std::cout << who << ">>>" << res << std::endl;
                logMessage(INFO, "%s >>> %s", who.c_str(), res.c_str());
                write(sock, res.c_str(), res.size());
            }
            else if (s == 0)
            {
                // std::cout << who << "quit, me too" << std::endl;
                logMessage(INFO, "%s quit, me too", who.c_str());
            }
            else
            {
                logMessage(ERROR, "read error: %s", strerror(errno));
                // std::cerr << "read error: " << strerror(errno) << std::endl;
            }
            close(sock);
        }
        ~TcpServer()
        {}
    private:
        int listensock_;
        uint16_t port_;
        bool quit_;
        func_t func_;
    };
}

